import { getCuesTopicPage } from "../../service/api/api-cues-topic";
import { listFestivalAndHoliday } from "../../service/api/api-home";
import { pageRecord } from "../../service/api/api-instruct-record";
import { calculateDaysAgo, handleErrCode } from "../../utils/util";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: true,//是否正在加载
    navBarHeight: 0,//导航栏高度
    access: {} as any,//用户权限
    modal: false,//线索征集分类
    currentUser: {},//当前用户完整信息
    isShowChange: true,//是否显示切换单位按钮
    festivalAndHolidayList: [],//节假日列表
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    noticeInstructs: [],
    functionList: [],//有权限的菜单入口列表
    previewDataUrlType: 'analysis',//数据统计
    run: 0,//列表状态
    mode: 0,//
    analysisUrl: 'http://localhost:8000/cues/analysisWx',//数据统计链接
    allList: [
      {
        name: "签到推广",// 功能名称
        icon: "icon_share_bold.png",// 功能图标
        access: ['showPromotion'],// 功能权限
        methods: "jumpToPromotion",// 功能跳转函数
        show: false,// 功能是否显示
      },
      {
        name: "线索征集",// 功能名称
        icon: "icon_plan_bold.png",// 功能图标
        access: ['showCues', 'showCuesActive'],// 功能权限
        methods: "jumpToReportClues",// 功能跳转函数
        show: false,// 功能是否显示
      },
      {
        name: "主动报送",// 功能名称
        icon: "icon_sign_in_bold.png",// 功能图标
        access: ['showCues', 'showCuesTopic'],// 功能权限
        methods: "jumpToActivelyReport",// 功能跳转函数
        show: false,// 功能是否显示
      },
      {
        name: "质效评估",// 功能名称
        icon: "icon_list_assess.png",// 功能图标
        access: ['showAssess'],// 功能权限
        methods: "jumpToAssess",// 功能跳转函数
        show: false,// 功能是否显示
      },

      {
        name: "宣传指令",// 功能名称
        icon: "icon_list_bold.png",// 功能图标
        access: ['showInstruct'],// 功能权限
        methods: "jumpToInstruct",// 功能跳转函数
        show: false,// 功能是否显示
      },
      // {
      //   name: "数据统计",// 功能名称
      //   icon: "icon_analysis.png",// 功能图标
      //   access: ['showInstruct'],// 功能权限
      //   methods: "jumpToAnalysis",// 功能跳转函数
      //   show: false,// 功能是否显示
      // },
      // {
      //   name: "数据统计",// 功能名称
      //   icon: "icon_list_bold.png",// 功能图标
      //   access: ['showInstruct'],// 功能权限
      //   methods: "jumpToAnalysis",// 功能跳转函数
      //   show: false,// 功能是否显示
      // },
      // {
      //   name: "技术支持",// 功能名称
      //   icon: "icon_help.png",// 功能图标
      //   access: ["showCues"],// 功能权限
      //   methods: "jumpToFeedback",// 功能跳转函数
      //   show: false,// 功能是否显示
      // },
    ],
    topicList: [],//线索征集的列表
  },
  //选中节假日
  onSelectFestivalAndHolidayList(e) {
    const index = e.currentTarget.dataset.index;
    this.data.festivalAndHolidayList[index].selected = !this.data.festivalAndHolidayList[index].selected;
    this.setData({
      festivalAndHolidayList: this.data.festivalAndHolidayList
    });
  },
  //获取节假日列表
  async loadListFestivalAndHoliday() {
    const res = await listFestivalAndHoliday()
    if (res.code === 0) {
      this.setData({
        festivalAndHolidayList: res.data
      })
    }
  },
  /**
   * 菜单点击跳转
   */
  funJump(e: any) {
    const { item = {} } = e.currentTarget.dataset || {};
    this[item.methods] && this[item.methods](item);
  },
  //跳到我的页面
  jumpToMy() {
    wx.navigateTo({
      url: '/pages/my/index',
    })
  },
  /**
    * 跳转技术支持
    */
  jumpToFeedback() {
    wx.navigateTo({
      url: '/pages/feedback/index',
    })
  },
  /**
     * 跳转数据统计
     */
  jumpToAnalysis() {
    const app = getApp();
    const url = encodeURIComponent(this.data.analysisUrl + '?phone=' + app.globalData.currentUser.phone)
    wx.navigateTo({
      url: '/pages/web/index?url=' + url + '&title=' + "数据统计" + '&type=' + this.data.previewDataUrlType
    })
  },
  /**
   * 跳转到签到推广
   */
  jumpToPromotion() {
    const access = this.data.access;
    if (access.showPromotion) {
      if (access.签到推广x列表x管理员) {// 管理员
        wx.navigateTo({
          url: '/pages/promotionAdmin/index',
        })
      } else {
        wx.navigateTo({
          url: '/pages/promotion/index',
        })
      }
    } else {
      handleErrCode('暂未开通改服务')
    }
  },
  /**
   * 跳转到主动报送
   */
  jumpToActivelyReport() {
    const access = this.data.access;
    if (access.showCues || access.showCuesActive) {
      wx.reLaunch({
        url: '/pages/cues/active/index',
      })
    } else {
      handleErrCode('暂未开通改服务')
    }
  },
  /**
   * 跳转到线索征集
   */
  jumpToReportClues() {
    const access = this.data.access;
    if (access.showCues || access.showCuesTopic) {
      if (access.线索上报x选题计划x配置x需求者) {// 管理员
        wx.reLaunch({
          url: '/pages/cues/topic/index',
        })
      } else {
        wx.reLaunch({
          url: '/pages/cues/topic/index',
        })
      }
    } else {
      handleErrCode('暂未开通改服务')
    }
  },
  /**
   * 跳转到宣传刊播
   */
  jumpToInstruct() {
    const access = this.data.access;
    if (access.showCues) {
      wx.reLaunch({
        url: '/pages/instruct/index',
      })
    } else {
      handleErrCode('暂未开通改服务')
    }
  },

  /**
   * 跳转到全媒体质效考核
   */
  jumpToAssess() {
    const access = this.data.access;
    if (true) {
      wx.navigateTo({
        url: '/pages/assess/render/index',
      })
    } else {
      handleErrCode('暂未开通改服务')
    }
  },
  //获取宣传指令列表
  async getInstructList() {
    const response = await pageRecord({ current: 1, pageSize: 5 });
    if (response.code === 0) {
      this.setData({
        noticeInstructs: response.data.data.map((item) => item.name),
      })
    }
  },
  //选择组织
  changeOrganization() {
    wx.reLaunch({
      url: `/pages/user/select/index?accountId=${this.data.currentUser.id}`
    })
  },
  /**
   * 钩子函数登录
   *
   * load的时候获取用户信息
   */
  onLoadCurrentUser() {
    const { globalData: { access, currentUser, navBarHeight, menuRight } } = getApp();
    let { allList: newList } = this.data;
    newList.forEach(item => {
      item.show = item.access.filter(acc => access[acc]).length > 0
    })
    if (currentUser.isHasSelectLoginOrganization == 0) {
      this.setData({
        isShowChange: false
      })
    }
    if (currentUser) {
      this.setData({
        access,
        functionList: newList.filter(item => item.show),
        currentUser,
        navBarHeight,
        menuRight,
        isLoading: false
      })
    }
    const mode = this.data.access.cuesTopicConfigManage ? 3 : this.data.access.cuesTopicConfigNeedDepartment || this.data.access.cuesTopicConfigNeedMedia ? 2 : 1;
    let run = undefined;
    if (!(this.data.access.cuesTopicConfigNeedDepartment || this.data.access.cuesTopicConfigNeedMedia)) {
      run = 1;
    }
    this.setData({
      mode,
      run
    })

    this.getTopicList({ mode: mode, current: 1, pageSize: 3, run: run });
    this.loadListFestivalAndHoliday()
    if (this.data.access.instructConfigManage) {
      this.getInstructList()
    }
  },
  //获取选题列表
  async getTopicList(params: { current: number, pageSize: number, mode: number, run: number }) {
    try {
      const response = await getCuesTopicPage({ current: params.current, pageSize: params.pageSize, mode: params.mode, run: params.run });
      const list = response.data.data
      list.forEach(item => {
        item.beforNow = calculateDaysAgo(item.createdTime)
      })
      this.setData({
        topicList: list,
      })
    } catch (error) {
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.onClickLogin(false);// 主动调用登录
    wx.showShareMenu({
      withShareTicket: true,
      menus: [
        'shareAppMessage', // 分享给朋友
        // 'shareTimeline',// 分享到朋友圈
      ]
    });
    //解决上报线索更新问题
    const topicId = wx.getStorageSync('topicId')
    const count = wx.getStorageSync('recordCount')
    const submitOrganizationCount = wx.getStorageSync('submitOrganizationCount')
    let isChange = true
    if (topicId && this.data.topicList) {
      const newList = this.data.topicList.map((item) => {
        if (item.id === topicId) {
          if (item.countSubmit === count && item.countSubmitOrganization === submitOrganizationCount) {
            isChange = false
            return
          } else {
            isChange = true
            item.countSubmit = count
            item.countSubmitOrganization = submitOrganizationCount
          }
        }
        return item
      })
      if (isChange) {
        this.setData({
          topicList: newList
        })
      }
    }
    // this.loadListFestivalAndHoliday()
    // this.getInstructList()
    // this.getTopicList({ mode: this.data.mode, current: 1, pageSize: 3, run: this.data.run });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
  //  组件所在页面的生命周期


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // this.onClickLogin(true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },


})